<template>
  <div>
    <van-loading
      color="#a6a6a6"
      style="
        z-index: 9999;
        height: 100vh;
        line-height: 100vh;
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
      "
      v-if="isLoading"
      type="spinner"
    />
    <div
      class="practice-test"
      :style="{
        background: '#f2f2f2',
        minHeight: '100vh',
        textAlign: 'left',
        opacity: !submit ? 1 : 0,
      }"
    >
      <div class="header">
        <div class="header-title van-ellipsis">{{ practiceTitle }}</div>
        <span class="header-time">{{ time }}</span>
        <div class="header-page">
          <span class="nav" @click="changePage('prev')">&#60;</span>
          <span style="color: #0043e7">
            {{ current_page + 1 }}
          </span>
          /{{ practiceList.length }}
          <span class="nav" @click="changePage('next')">&#62;</span>
        </div>
      </div>
      <div class="content">
        <van-swipe
          ref="swiper"
          style="
            min-height: calc(100vh - 80px);
            margin: 0 25px;
            box-sizing: border-box;
          "
          :show-indicators="false"
          @change="onChange"
        >
          <van-swipe-item
            v-for="(practiceItem, index) in practiceList"
            :key="index"
          >
            <div class="title" v-html="practiceItem.title"></div>
            <div class="select-options">
              <van-checkbox-group :value="answer.answer">
                <van-checkbox
                  @click="checkChange(item.value)"
                  v-for="(item, index) in practiceItem.selectOptions"
                  :key="index + item.text"
                  :name="item.value"
                >
                  <div
                    :class="{
                      green:
                        (!answer.status &&
                          answer.answer.indexOf(item.value) !== -1) ||
                        (answer.status &&
                          practiceItem.correctValue.indexOf(item.value) !== -1),
                      error:
                        answer.status &&
                        answer.answer.indexOf(item.value) !== -1 &&
                        practiceItem.correctValue.indexOf(item.value) === -1,
                    }"
                  >
                    {{ item.text }}
                  </div>
                  <template #icon="props">
                    <div
                      :class="{
                        img_icon: true,
                        green_border:
                          (!answer.status &&
                            answer.answer.indexOf(item.value) !== -1) ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1),
                      }"
                      :style="{
                        borderColor:
                          (!answer.status &&
                            answer.answer.indexOf(item.value) !== -1) ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1)
                            ? '#54d100'
                            : '#000',
                      }"
                    >
                      <div
                        :style="`background-color:${
                          (!answer.status &&
                            answer.answer.indexOf(item.value) !== -1) ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1)
                            ? '#54d100'
                            : '#000'
                        }`"
                        v-show="
                          props.checked ||
                          (answer.status &&
                            practiceItem.correctValue.indexOf(item.value) !==
                              -1)
                        "
                      ></div>
                    </div>
                  </template>
                </van-checkbox>
              </van-checkbox-group>
              <div
                v-if="practiceList[current_page].type === 2"
                class="submit-button"
                @click="confirm"
              ></div>
            </div>
            <div v-show="answer.status" class="answer green">
              参考答案：{{ valueText }}
            </div>
            <div
              v-show="answer.status"
              class="answer-desc"
              v-html="
                practiceItem && practiceItem.analysis
                  ? '参考解析' + practiceItem.analysis
                  : '参考解析: 暂无'
              "
            >
              参考解析：小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼
              小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼小明是傻逼
            </div>
          </van-swipe-item>
        </van-swipe>
      </div>
      <div class="operation">
        <!-- <div @click="collect"><img src="../icon/icon4.png" alt="" /> 收藏</div> -->
        <div @click="lookAnswer">
          <img src="../icon/icon.png" alt="" />答题卡
        </div>
        <div @click="submitPaper">
          <img src="../icon/icon2.png" alt="" />交卷
        </div>
      </div>
      <div class="back" @click="$router.go(-1)">返回上一页</div>
      <van-popup
        v-model="lookAnswerStatus"
        position="bottom"
        :overlay-style="{ background: 'rgba(0, 0, 0, 0.3)' }"
        round
      >
        <div class="answer-header">
          <div class="left">
            <div>
              <img src="../icon/icon.png" alt="" /><span
                style="color: #0043e7"
                >{{
                  answerMake.filter((item) => item !== undefined).length
                }}</span
              >/{{ practiceList.length }}
            </div>
            <div style="margin-left: 10px; color: #54d100">
              <img src="../icon/icon1.png" alt="" />{{
                answerMake.filter((item) => item).length
              }}
            </div>
            <div style="margin-left: 10px; color: #ff1f1a">
              <img src="../icon/icon3.png" alt="" />{{
                answerMake.filter((item) => item === false).length
              }}
            </div>
          </div>
          <div class="right" @click="submitPaper">
            <img src="../icon/icon2.png" alt="" />交卷
          </div>
        </div>
        <div class="answer-content">
          <div
            v-for="(item, index) in practiceList"
            :key="item.id"
            @click="
              () => {
                $refs.swiper.swipeTo(index);
                lookAnswerStatus = !lookAnswerStatus;
              }
            "
            :style="`${
              answerMake[index] !== undefined
                ? `background-color: ${
                    answerMake[index] ? '#54d100' : '#ff1f1a'
                  };color:#fff`
                : ''
            }`"
          >
            {{ index + 1 }}
          </div>
        </div>
      </van-popup>
    </div>

    <answer-result
      :answerMake="answerMake"
      :count-num="practiceList.length"
      :title="$route.query.pidTitle"
      :desc="$route.query.title"
      :allScore="allScore"
      :score="score"
      @changeCurrentPage="changeCurrentPage"
      @resetPractice="resetPractice"
      v-show="submit"
      :style="{
        zIndex: '999',
        position: 'fixed',
        top: '0',
        left: '0',
        opacity: submit ? 1 : 0,
      }"
    />
    <van-dialog v-model="show" :show-confirm-button="false">
      <div class="dialog_wrapper">
        <p>
          系统检测到您还未开通权限，需要开通题库权限请联系我们的工作人员缴费开通:
        </p>
        <span>{{ teacherInfo.name }}{{ teacherInfo.phone }}(微信同号)</span>
        <img :src="teacherInfo.link" />
        <span style="font-weight: bold; font-size: 20px"
          >长按二维码可添加微信</span
        >
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { Toast } from "vant";
import AnswerResult from "../associate/AnswerResult";
export default {
  data() {
    this.setTimeoutId = null;
    return {
      practiceTitle: "", // 页面的标题
      current_page: 0, // 当前页数
      total_page: 0, // 总页数
      practiceList: [], // 练习习题列表
      answerList: [], // 用户的答案记录列表
      answer: { status: false, answer: [] }, // 用户当前题的做题的答案
      answerMake: [], // 记录正误的数组
      lookAnswerStatus: false, // 查看答题卡
      submit: false, // 交卷
      allScore: 0,
      score: 0,
      isLoading: false, // 加载提示
      teacherInfo: {}, // 缴费教师的信息
      show: false, // 显示弹出缴费
      time: "", // 所用时长
    };
  },
  components: {
    AnswerResult,
  },
  mounted() {
    let time = 0;
    this.setInterval = setInterval(() => {
      let s = this.showNum(time % 60);
      let m = this.showNum(parseInt(time / 60) % 60);
      let h = this.showNum(parseInt(time / 60 / 60));
      this.time = `${h}:${m}:${s}`;
      time++;
    }, 1000);
    this.loadData();
    this.$http.get("/api/mzcy/tklb/qianxian").then((res) => {
      // console.log(res.data, "联系我们");
      this.teacherInfo = res.data;
    });
  },
  watch: {
    answerMake: {
      deep: true,
      immediate: true,
      handler(val) {
        console.log(val, "val");
        this.isABC(val);
      },
    },
    answerList: {
      deep: true,
      handler(val) {
        // console.log(val, "val");
        // 计算错了多少道题目
        val.map((item, index) => {
          if (item.answer.length <= 0) return;
          let current = [...item.answer].sort().join(",");
          let correct = (this.practiceList[index]
            ? [...this.practiceList[index].correctValue]
            : []
          )
            .sort()
            .join(",");
          // // console.log(current == correct, index);
          if (current === correct) {
            this.answerMake[index] = true;
          } else {
            this.answerMake[index] = false;
          }
        });
      },
    },
  },
  computed: {
    valueText() {
      // console.log(this.practiceList[this.current_page]);
      return this.practiceList[this.current_page].correctValue
        .map((item) => {
          if (item === 0) item = "A";
          if (item === 1) item = "B";
          if (item === 2) item = "C";
          if (item === 3) item = "D";
          if (item === 4) item = "E";
          if (item === 5) item = "F";
          if (item === 6) item = "G";
          if (item === 7) item = "H";
          return item;
        })
        .join(",");
    },
  },
  methods: {
    //封装一个处理单位数字的函数
    showNum(num) {
      if (num < 10) {
        return "0" + num;
      }
      return num;
    },
    isABC(val) {
      if (val.filter((item) => item !== undefined).length >= 6) {
        let status = this.$route.query.status;
        if (status != 1) {
          this.show = true;
        }
      }
    },
    submitPaper() {
      this.allScore =
        this.practiceList instanceof Array &&
        this.practiceList.reduce((pre, current, currentIndex) => {
          // console.log(pre, current, currentIndex);
          if (this.answerMake[currentIndex]) this.score += current.score || 0;
          return pre + (current.score || 0);
        }, 0);
      // console.log(this.score, this.allScore);
      this.submit = !this.submit;
      this.lookAnswerStatus = false;
    },
    // 重置做题
    resetPractice() {
      if (this.answerList.filter((item) => item.status).length <= 0) {
        this.practiceList = [];
        this.answerList = [];
        this.answer = { status: false, answer: [] };
        this.answerMake = [];
        this.loadData();
        this.submit = !this.submit;
        return false;
      }
      this.$http
        .get(
          "/api/mzcy/tklb/record_reset?" +
            "xclass_id=" +
            this.$route.query.pid +
            "&type=" +
            this.$route.query.type
        )
        .then((res) => {
          if (res.data.code !== 1)
            return Toast({
              message: res.data.msg || "失败",
              duration: 1000,
              overlay: false,
              forbidClick: true,
            });
          this.practiceList = [];
          this.answerList = [];
          this.answer = { status: false, answer: [] };
          this.answerMake = [];
          this.loadData();
          this.submit = !this.submit;
        });
    },
    // 改变页数
    changeCurrentPage(index) {
      this.$refs.swiper.swipeTo(index);
      this.submit = !this.submit;
    },
    // 收藏
    collect() {
      this.$http
        .get(
          "/api/mzcy/tklb/stscjl?id=" + this.practiceList[this.current_page].id
        )
        .then((res) => {
          Toast({
            duration: 1000,
            message: res.data.msg,
            overlay: false,
            forbidClick: true,
          });
        });
    },
    // 答题卡
    lookAnswer() {
      this.lookAnswerStatus = true;
      // console.log("查看答题卡");
    },
    checkChange(value) {
      // console.log(value, "value");
      if (this.practiceList[this.current_page].type !== 2) {
        if (this.answer.answer.length > 0) {
          const answer = [];
          answer.push(value);
          this.answer.answer = answer;
        } else {
          this.answer.answer.push(value);
        }
        let current = [...this.answer.answer].sort().join(",");
        let correct = [...this.practiceList[this.current_page].correctValue]
          .sort()
          .join(",");
        if (current === correct) {
          this.answerMake[this.current_page] = true;
          this.answerMake = [...this.answerMake];
          Toast({
            duration: 1000,
            message: "回答正确",
            overlay: false,
            forbidClick: true,
          });
          // if (this.setTimeoutId) {
          //   clearTimeout(this.setTimeoutId);
          //   this.setTimeoutId = null;
          // }
          // this.setTimeoutId = setTimeout(() => {
          //   this.$refs.swiper.next();
          // }, 2100);
        } else {
          Toast({
            duration: 1000,
            message: "回答错误，已加入错题库",
            overlay: false,
            forbidClick: true,
          });
          // 加入错题
          this.$http.get(
            "/api/mzcy/question/adderrorques?id=" +
              this.practiceList[this.current_page].id +
              "&value=" +
              this.answer.answer.join("")
          );
          this.answerMake[this.current_page] = false;
          this.answerMake = [...this.answerMake];
          // if (this.setTimeoutId) {
          //   clearTimeout(this.setTimeoutId);
          //   this.setTimeoutId = null;
          // }
          // this.setTimeoutId = setTimeout(() => {
          //   this.$refs.swiper.next();
          // }, 2100);
        }
        this.$http.get(
          "/api/mzcy/tklb/record_into?id=" +
            this.practiceList[this.current_page].id +
            "&value=" +
            this.answer.answer.join("") +
            "&xclass_id=" +
            this.$route.query.pid +
            "&type=" +
            this.$route.query.type
        );

        this.answer.status = true;
        this.answerList[this.current_page] = {
          status: true,
          answer: [...this.answer.answer],
        };
      } else {
        let index = this.answer.answer.indexOf(value);
        if (index !== -1)
          this.answer.answer = this.answer.answer
            .slice(0, index)
            .concat(this.answer.answer.slice(index + 1));
        if (index === -1) this.answer.answer.push(value);
      }
    },
    changePage(type) {
      this.$refs.swiper[type]();
    },
    onChange(index) {
      // console.log(index);
      this.current_page = index;
      // console.log(this.answerList);
      this.answer = {
        status: this.answerList[this.current_page].status,
        answer: [...this.answerList[this.current_page].answer],
      };
      // console.log(this.answer);
    },
    confirm() {
      if (this.answer.answer.length <= 0) {
        Toast({
          duration: 1000,
          message: "请选择你的答案再确认",
          overlay: false,
          forbidClick: true,
        });
        return;
      }
      this.$http.get(
        "/api/mzcy/tklb/record_into?id=" +
          this.practiceList[this.current_page].id +
          "&value=" +
          this.answer.answer.join("") +
          "&xclass_id=" +
          this.$route.query.pid +
          "&type=" +
          this.$route.query.type
      );
      let current = [...this.answer.answer].sort().join(",");
      let correct = [...this.practiceList[this.current_page].correctValue]
        .sort()
        .join(",");
      if (current === correct) {
        this.answerMake[this.current_page] = true;
        this.answerMake = [...this.answerMake];
        Toast({
          duration: 1000,
          message: "回答正确",
          overlay: false,
          forbidClick: true,
        });

        // setTimeout(() => {
        //   this.$refs.swiper.next();
        // }, 2100);
      } else {
        Toast({
          duration: 1000,
          message: "回答错误，已加入错题库",
          overlay: false,
          forbidClick: true,
        });
        // 加入错题
        this.$http.get(
          "/api/mzcy/question/adderrorques?id=" +
            this.practiceList[this.current_page].id +
            "&value=" +
            this.answer.answer.join("")
        );

        this.answerMake[this.current_page] = false;
        this.answerMake = [...this.answerMake];
        // if (this.setTimeoutId) {
        //   clearTimeout(this.setTimeoutId);
        //   this.setTimeoutId = null;
        // }
        // this.setTimeoutId = setTimeout(() => {
        //   this.$refs.swiper.next();
        // }, 2100);
      }
      // this.$refs.swiper.next();
      this.answer.status = true;
      this.answerList[this.current_page] = {
        status: true,
        answer: [...this.answer.answer],
      };
      // console.log(this.answerList[this.current_page]);
      // console.log(this.answerList);
    },
    loadData() {
      this.isLoading = true;
      // 页面的标题
      this.practiceTitle = this.$route.query.title || "标题";
      this.$http
        .get(`/api/mzcy/question/questions?id=${this.$route.query.type}`)
        .then((res) => {
          this.isLoading = false;
          // // console.log(res.data, "res");
          if (res.status === 200) {
            // 当前页数
            this.current_page = parseInt(res.data.current_page)
              ? parseInt(res.data.current_page) - 1
              : 0;
            // 总页数
            this.total_page = res.data.total;
            // 练习习题列表
            let practiceList = [];
            practiceList = res.data.data.map((item) => {
              // // console.log(item);
              // 选项
              let selectOptions = [];
              // 答案
              let correctValue = [];
              for (var key in item.xz) {
                // // console.log(key, "key");
                let val = key.split("value")[1];
                if (val === "a") val = 0;
                if (val === "b") val = 1;
                if (val === "c") val = 2;
                if (val === "d") val = 3;
                if (val === "e") val = 4;
                if (val === "f") val = 5;
                if (val === "g") val = 6;
                if (val === "h") val = 7;
                selectOptions.push({ value: val, text: item.xz[key] });
              }
              // // console.log(selectOptions);
              // 多选
              if (item.type === 2) {
                correctValue = item.value;
              } else {
                // 单选
                correctValue.push(item.value);
              }

              // // console.log(item.record, "item");
              let answer =
                item.record.answer &&
                item.record.answer.split("").map((item) => {
                  // // console.log(item);
                  if (item === "A") return 0;
                  if (item === "B") return 1;
                  if (item === "C") return 2;
                  if (item === "D") return 3;
                  if (item === "E") return 4;
                  if (item === "F") return 5;
                  if (item === "G") return 6;
                  if (item === "H") return 7;
                });
              this.answerList.push({
                answer: answer || [],
                status: !!answer && answer.length > 0,
              });
              this.answer = {
                status: this.answerList[this.current_page].status,
                answer: [...this.answerList[this.current_page].answer],
              };
              // // console.log(this.answerList, "111");
              // type  题型
              // title 题目
              // record 用户答案
              // analysis 题目解析
              return {
                id: item.id,
                selectOptions,
                correctValue,
                type: item.type,
                title: item.title,
                analysis: item.analysis,
                score: item.number,
              };
            });
            // // console.log(practiceList);
            this.practiceList = practiceList;
          }
        });
    },
  },
  beforeDestroy() {
    clearInterval(this.setInterval);
  },
};
</script>

<style>
@import url("../css/practiceTest.css");
</style>
